<template>
  <div>
    <el-form ref="form" label-width="80px" :model="sku" :rules="rules">
      <el-form-item label="SPU名称">
        <h3>{{ spu.spuName }}</h3></el-form-item
      >
      <el-form-item label="SKU名称" prop="skuName">
        <el-input placeholder="请输入SKU名称" v-model="sku.skuName"> </el-input>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number
          placeholder="请输入SKU价格"
          v-model="sku.price"
          controls-position="right"
          :min="0"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="重量" prop="weight">
        <el-input-number
          placeholder="请输入SKU重量"
          v-model="sku.weight"
          controls-position="right"
          :min="0"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="SKU描述" prop="skuDesc">
        <el-input
          placeholder="请输入SKU描述"
          type="textarea"
          v-model="sku.skuDesc"
          :rows="3"
        ></el-input>
      </el-form-item>
      <!--  skuAttrValueList: [
          // {
          //   attrId: 0,
          //   attrName: "string",
          //   valueId: 0,
          //   valueName: "string",
          // },
        ], -->
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row :gutter="20" class="row-md">
          <el-col
            :span="8"
            v-for="(attr, index) in attrList"
            :key="attr.id"
            class="add-sku-col"
          >
            <span>{{ attr.attrName }}</span>
            <el-select v-model="sku.skuAttrValueList[index]">
              <el-option
                v-for="attrValue in attr.attrValueList"
                :key="attrValue.id"
                :label="attrValue.valueName"
                :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <!-- 
   skuSaleAttrValueList: [
          // {
          //   saleAttrId: 0,
          //   saleAttrName: "string",
          //   saleAttrValueId: 0,
          //   saleAttrValueName: "string",
          // },
        ],
 -->

      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row :gutter="20">
          <el-col
            :span="8"
            v-for="(saleAttr, index) in spu.spuSaleAttrList"
            :key="saleAttr.id"
          >
            <span>{{ saleAttr.saleAttrName }}&emsp;</span>
            <el-select v-model="sku.skuSaleAttrValueList[index]">
              <el-option
                v-for="saleValue in saleAttr.spuSaleAttrValueList"
                :key="saleValue.id"
                :label="saleValue.saleAttrValueName"
                :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleValue.id}:${saleValue.saleAttrValueName}`"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="SKU图片" prop="skuImageList">
        <el-table
          ref="multipleTable"
          :data="spuImageList"
          tooltip-effect="dark"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.imgUrl" alt="row.imgName" class="sku-table-img" />
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称"> </el-table-column>
          <el-table-column label="操作" prop="skuDefaultImg">
            <template v-slot="{ row }">
              <el-button
                size="mini"
                v-show="row.isDefault === '0'"
                type="primary"
                class="el-icon-plus"
                @click="setDefalut(row)"
              >
                设置默认值</el-button
              >
              <el-button
                disabled
                v-show="row.isDefault === '1'"
                size="mini"
                type="success"
                >默认图片</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { reqAttrInfoList } from "@/api/production/attr";
import { reqSpuImageList, reqSaveSku } from "@/api/production/sku";
import { reqGetSpuById } from "@/api/production/spu";
export default {
  name: "AddSku",
  data() {
    return {
      spu: {},
      attrList: [],
      spuImageList: [],
      sku: {
        category3Id: 0,
        price: 0,
        spuId: 0, //商品id在vuexli保存
        tmId: 0, //品牌id
        weight: "",
        skuName: "", //sku名称
        skuDefaultImg: "", //sku默认照片地址
        skuDesc: "", //sku描述
        skuAttrValueList: [
          // {
          //   attrId: 0,
          //   attrName: "string",
          //   valueId: 0,
          //   valueName: "string",
          // },
        ],
        skuImageList: [
          // {
          //   imgName: "string",
          //   imgUrl: "string",
          //   isDefault: "string",
          //   skuId: 0,
          //   spuImgId: 0,
          // },
        ],
        skuSaleAttrValueList: [
          // {
          //   saleAttrId: 0,
          //   saleAttrName: "string",
          //   saleAttrValueId: 0,
          //   saleAttrValueName: "string",
          // },
        ],
      },
      rules: {
        skuName: [
          { required: true, message: "请输入SKU名称", trigger: "blur" },
        ],
        price: [{ required: true }],
        weight: [
          { required: true, validator: this.inputNumer, trigger: "blur" },
        ],
        // skuDefaultImg: [{ required: true, validator: this.defalutImgVali }],
        skuDesc: [
          { required: true, message: "请输入SPU描述", trigger: "blur" },
        ],
        skuAttrValueList: [
          {
            required: true,
            validator: this.skuAttrValueListVali,
            trigger: "change",
          },
        ],
        skuImageList: [
          {
            required: true,
            validator: this.skuImageListVali,
            trigger: "change",
          },
        ],
        skuSaleAttrValueList: [
          {
            required: true,
            validator: this.skuSaleAttrValueListVali,
            trigger: "change",
          },
        ],
      },
    };
  },
  async mounted() {
    // 需要三个请求，1.获取spu的信息和销售属性，2.获得skuImageList
    // 3.平台属性 通过请求获取attrINfoList,获取相关属性 2,13,61 发请求是异步的加await
    let { spuId, category1Id, category2Id, category3Id } = this;
    let [attrListResp, spuImageListResp, spuResp] = await Promise.allSettled([
      reqAttrInfoList({
        category1Id,
        category2Id,
        category3Id,
      }),
      reqSpuImageList(spuId),
      reqGetSpuById(spuId),
    ]);
    if (attrListResp.status === "fulfilled") {
      this.attrList = attrListResp.value;
    } else {
      this.$message({
        type: "error",
        message: "获取属性值列表失败",
      });
    }

    if (spuImageListResp.status === "fulfilled") {
      this.spuImageList = spuImageListResp.value.map((img) => {
        return {
          ...img,
          isDefault: "0",
        };
      });
    } else {
      this.$message({
        type: "error",
        message: "获取spu照片列表失败",
      });
    }
    if (spuResp.status === "fulfilled") {
      this.spu = spuResp.value;
    } else {
      this.$message({
        type: "error",
        message: "获取spu照片列表失败",
      });
    }
  },
  computed: {
    ...mapState("spu", ["spuId"]),
    ...mapState("category", ["category1Id", "category2Id", "category3Id"]),
  },
  methods: {
    // 3.收集点击的图片列表
    handleSelectionChange(val) {
      this.sku.skuImageList = val;
    },
    //1.设置默认值
    setDefalut(row) {
      // 1.1在初始化的时候添加一个isCheck属性 '1' 设置默认 "0":反之
      // 1.2把之前都清掉
      this.spuImageList.forEach((img) => (img.isDefault = "0"));
      // 1.3给当前添加,由于传递的是当前行的引用地址，可以直接对响应数据进行修改，
      row.isDefault = "1";
      this.sku.skuDefaultImg = row.imgUrl;
    },
    // 2.提交表单
    submit() {
      //2.1对skuAttrValueList整理
      // 2.3 对skuSaleAttrValueList整理
      this.$refs.form.validate(async (vali) => {
        const { category3Id, spuId } = this;
        let {
          price,
          weight,
          skuName,
          skuDefaultImg,
          skuDesc,
          skuAttrValueList,
          skuImageList,
          skuSaleAttrValueList,
        } = this.sku;
        const { tmId } = this.spu;
        // 数据处理，去掉空格，把数据切割
        skuAttrValueList = skuAttrValueList.filter(Boolean).map((attr) => {
          const [attrId, attrName, valueId, valueName] = attr.split(":");
          return {
            attrId,
            attrName,
            valueId,
            valueName,
          };
        });
        skuSaleAttrValueList = skuSaleAttrValueList
          .filter(Boolean)
          .map((saleValue) => {
            const [
              saleAttrId,
              saleAttrName,
              saleAttrValueId,
              saleAttrValueName,
            ] = saleValue.split(":");
            return {
              saleAttrId,
              saleAttrName,
              saleAttrValueId,
              saleAttrValueName,
            };
          });
        const data = {
          category3Id,
          price,
          spuId, //商品id在vuexli保存
          tmId, //品牌id
          weight,
          skuName, //sku名称
          skuDefaultImg, //sku默认照片地址
          skuDesc, //sku描述
          skuAttrValueList,
          skuImageList,
          skuSaleAttrValueList,
        };
        if (vali) {
          // 清除校验结果
          this.$refs.form.clearValidate("skuImageListVali");
          await reqSaveSku(data);
          this.$message({
            type: "success",
            message: "添加SKU成功！",
          });
          this.cancel();
        } else {
          this.$message({
            type: "error",
            message: "添加SKU失败",
          });
        }
      });
    },
    cancel() {
      this.$emit("updateIsShow", 1);
    },

    skuAttrValueListVali(rule, value, callback) {
      //至少有一个平台属性
      let isHasSkuAttrValue = this.sku.skuAttrValueList.some(
        (item) => item !== undefined
      );
      if (!isHasSkuAttrValue) {
        callback("至少选择一个平台属性");
        return;
      }
      callback();
    },
    skuImageListVali(rule, value, callback) {
      if (this.sku.skuImageList.length <= 0) {
        callback("至少在照片列表里选择一张");
        return;
      }
      //校验默认照片
      if (!this.sku.skuDefaultImg) {
        callback("请选择默认图片");
        return;
      }
      callback();
    },
    skuSaleAttrValueListVali(rule, value, callback) {
      let isHasSaleAttrValue = this.sku.skuSaleAttrValueList.some(
        (item) => item !== undefined
      );
      if (!isHasSaleAttrValue) {
        callback("至少有一个销售属性");
        return;
      }

      callback();
    },
    inputNumer(rule, value, callback) {
      if (this.spu.weight <= 0 || this.spu.price <= 0) {
        callback("请输入重量或是价格");
        return;
      }
      callback();
    },
  },
};
</script>

<style scoped>
.add-sku-col {
  margin-bottom: 10px;
}
.sku-table-img {
  width: 150px;
  height: 150px;
}
</style>